package com.haixiaoke.saas.lock.service.impl;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.haixiaoke.saas.auth.ali.service.AliAuthService;
import com.haixiaoke.saas.common.config.DevicesConfig;
import com.haixiaoke.saas.common.config.sms.SmsConfig;
import com.haixiaoke.saas.common.constant.HouseMemberConstants;
import com.haixiaoke.saas.common.constant.HttpStatus;
import com.haixiaoke.saas.common.constant.LockConstants;
import com.haixiaoke.saas.common.core.domain.AjaxResult;
import com.haixiaoke.saas.common.core.page.TableDataInfo;
import com.haixiaoke.saas.common.exception.ServiceException;
import com.haixiaoke.saas.common.utils.DateUtils;
import com.haixiaoke.saas.common.utils.sms.SmsUtils;
import com.haixiaoke.saas.department.domain.Tenant;
import com.haixiaoke.saas.department.service.ITenantService;
import com.haixiaoke.saas.house.domain.House;
import com.haixiaoke.saas.house.service.IHouseService;
import com.haixiaoke.saas.houseMember.domain.HouseMember;
import com.haixiaoke.saas.houseMember.service.IHouseMemberService;
import com.haixiaoke.saas.lock.domain.*;
import com.haixiaoke.saas.lock.mapper.HouseLockMapper;
import com.haixiaoke.saas.lock.service.*;
import com.haixiaoke.saas.order.domain.Order;
import com.haixiaoke.saas.order.service.IOrderService;
import com.haixiaoke.saas.user.domain.BizUserBusiness;
import com.haixiaoke.saas.user.domain.UserConsumer;
import com.haixiaoke.saas.user.service.IBizUserBusinessService;
import com.haixiaoke.saas.user.service.IUserConsumerService;
import com.haixiaoke.saas.workOrder.domain.WorkOrder;
import com.haixiaoke.saas.workOrder.domain.WorkOrderPwdRecord;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 房间锁信息Service业务层处理
 *
 * @author qixi
 * @date 2024-07-25
 */
@Service
@Slf4j
public class HouseLockServiceImpl implements IHouseLockService {
    @Autowired
    private HouseLockMapper houseLockMapper;

    @Autowired
    private IHouseService houseService;

    @Autowired
    private DevicesConfig devicesConfig;

    @Autowired
    private IOrderService orderService;

    @Autowired
    private ILockFaceService lockFaceService;

    @Autowired
    private ILockPwdService lockPwdService;

    @Autowired
    private LockDevicesService lockDevicesService;

    @Autowired
    private IHouseLockSettingService houseLockSettingService;

    @Autowired
    private IBizUserBusinessService bizUserBusinessService;

    @Autowired
    private IHouseMemberService houseMemberService;

    @Autowired
    private ITenantService tenantService;

    @Autowired
    private ILockFreezeLogService lockFreezeLogService;
    @Autowired
    private IUserConsumerService userConsumerService;

    @Autowired
    private AliAuthService aliAuthService;

    @Autowired
    private SmsUtils smsUtils;
    @Autowired
    private SmsConfig smsConfig;


    /**
     * 查询房间锁信息
     *
     * @param lockId 房间锁信息主键
     * @return 房间锁信息
     */
    @Override
    public HouseLock selectHouseLockByLockId(Long lockId) {
        return houseLockMapper.selectHouseLockByLockId(lockId);
    }

    /**
     * 查询房间锁信息列表
     *
     * @param houseLock 房间锁信息
     * @return 房间锁信息
     */
    @Override
    public List<HouseLock> selectHouseLockList(HouseLock houseLock) {
        return houseLockMapper.selectHouseLockList(houseLock);
    }

    /**
     * 新增房间锁信息
     *
     * @param houseLock 房间锁信息
     * @return 结果
     */
    @Override
    public int insertHouseLock(HouseLock houseLock) {
        houseLock.setCreateTime(DateUtils.getNowDate());
        return houseLockMapper.insertHouseLock(houseLock);
    }

    /**
     * 修改房间锁信息
     *
     * @param houseLock 房间锁信息
     * @return 结果
     */
    @Override
    public int updateHouseLock(HouseLock houseLock) {
        houseLock.setUpdateTime(DateUtils.getNowDate());
        return houseLockMapper.updateHouseLock(houseLock);
    }

    /**
     * 批量删除房间锁信息
     *
     * @param lockIds 需要删除的房间锁信息主键
     * @return 结果
     */
    @Override
    public int deleteHouseLockByLockIds(Long[] lockIds) {
        return houseLockMapper.deleteHouseLockByLockIds(lockIds);
    }

    /**
     * 删除房间锁信息信息
     *
     * @param lockId 房间锁信息主键
     * @return 结果
     */
    @Override
    public int deleteHouseLockByLockId(Long lockId) {
        return houseLockMapper.deleteHouseLockByLockId(lockId);
    }

    @Override
    @Transactional
    public int createHouseLock(HouseLock houseLock) {
        String houseId = houseLock.getHouseId();
        House house = houseService.selectHouseById(houseId);
        if (ObjectUtil.isNull(house)) {
            throw new ServiceException("房屋不存在");
        }

        Tenant tenant = tenantService.selectDepartmentByDepId(houseLock.getTenantId());
        if (ObjectUtil.isNull(tenant)) {
            throw new ServiceException("机构不存在");
        }
        houseLock.setTenantName(tenant.getTenantName());

        lockDevicesService.createSmartLock(houseLock);
        houseLock.setHouseAddress(house.getPremisesAddress());
        Long houseManagerId = house.getHouseManagerId();
        BizUserBusiness bizUserBusiness = bizUserBusinessService.selectBizUserBusinessByUserId(houseManagerId, houseLock.getTenantId());
        houseLock.setCreateTime(DateUtils.getNowDate());
        int i = 0;
        List<Order> orders = orderService.selectEffectiveOrderByHouseId(houseId);
        if (CollectionUtil.isEmpty(orders)) {
            houseLock.setLockState(HouseLock.LOCK_STATE_NORMAL);
            i = houseLockMapper.insertHouseLock(houseLock);
            String identification = devicesConfig.getIdentification();
            // 没有订单添加管理员
            LockFace lockFace = new LockFace();
            lockFace.setLockId(houseLock.getLockId());
            lockFace.setHouseId(houseId);
            lockFace.setImg(bizUserBusiness.getFaceImage());
            lockFace.setUserName(bizUserBusiness.getUserName());
            lockFace.setUserId(bizUserBusiness.getUserId());
            lockFace.setUserType(LockConstants.USER_TYPE_MANAGER);
            lockFace.setIdentification(identification);
            lockFace.setFaceState(LockConstants.FACE_STATE_ENABLED);
            lockFace.setCreateBy(houseLock.getTenantName());

            lockDevicesService.createLockFace(bizUserBusiness.getFaceImage(), houseLock.getMac(), identification);

            lockFaceService.insertLockFace(lockFace);
        } else {

            HouseLockSetting houseLockSetting = houseLockSettingService.selectLockSettingByTenantId(houseLock.getTenantId());
            for (Order order : orders) {
                Date checkOutTime = order.getCheckOutTime();

                String identification = devicesConfig.getIdentification();
                LockFace lockFace = new LockFace();
                lockFace.setHouseId(houseId);
                lockFace.setImg(bizUserBusiness.getFaceImage());
                lockFace.setUserName(bizUserBusiness.getUserName());
                lockFace.setUserId(bizUserBusiness.getUserId());
                lockFace.setUserType(LockConstants.USER_TYPE_MANAGER);
                lockFace.setIdentification(identification);
                lockFace.setCreateBy(houseLock.getTenantName());

                if (HouseLockSetting.AUTO_FROZEN_STATE_OFF.equals(houseLockSetting.getAutoFrozenState())
                        || DateUtil.compare(DateUtils.getNowDate(), checkOutTime) < 0) {
                    houseLock.setLockState(HouseLock.LOCK_STATE_NORMAL);
                    i = houseLockMapper.insertHouseLock(houseLock);
                    addHouseMemberFace(order, houseLock);
                    lockFace.setFaceState(LockConstants.FACE_STATE_DISABLE);
                } else {
                    houseLock.setLockState(HouseLock.LOCK_STATE_FROZEN);
                    i = houseLockMapper.insertHouseLock(houseLock);
                    lockDevicesService.createLockFace(lockFace.getImg(), houseLock.getMac(), identification);
                    lockFace.setFaceState(LockConstants.FACE_STATE_ENABLED);
                }
                lockFace.setLockId(houseLock.getLockId());
                lockFaceService.insertLockFace(lockFace);
            }
        }

        if (HouseLock.LOCK_STATE_FROZEN.equals(houseLock.getLockState())) {
            LockFreezeLog lockFreezeLog = new LockFreezeLog();
            lockFreezeLog.setLockId(houseLock.getLockId());
            lockFreezeLog.setFreezeType(LockConstants.FREEZE_TYPE_FREEZE);
            lockFreezeLog.setOperationType(LockConstants.FREEZE_OPERATE_TYPE_AUTO);
            lockFreezeLog.setCreateBy(houseLock.getCreateBy());
            lockFreezeLogService.insertLockFreezeLog(lockFreezeLog);
        }
        return i;
    }

    /**
     * 已实名添加订单入住授权人脸
     *
     * @param order
     * @param houseLock
     */
    private void addHouseMemberFace(Order order, HouseLock houseLock) {
        List<HouseMember> houseMembers = houseMemberService.selectHouseMemberListByOrderId(order.getOrderId());

        for (HouseMember houseMember : houseMembers) {
            if (HouseMemberConstants.AUTH_STATE_YES.equals(houseMember.getAuthState())) {
                String identification = devicesConfig.getIdentification();
                LockFace lockFace = new LockFace();
                lockFace.setLockId(houseLock.getLockId());
                lockFace.setOrderId(order.getOrderId());
                lockFace.setHouseId(houseLock.getHouseId());
                lockFace.setImg(houseMember.getFacePhoto());
                lockFace.setUserName(houseMember.getMemberName());
                lockFace.setUserId(houseMember.getUserId());
                lockFace.setUserType(LockConstants.USER_TYPE_TENANT);
                lockFace.setIdentification(identification);
                lockFace.setFaceState(LockConstants.FACE_STATE_ENABLED);
                lockFace.setMac(houseLock.getMac());
                lockFace.setCreateBy(houseLock.getTenantName());

                lockDevicesService.createLockFace(houseMember.getFacePhoto(), houseLock.getMac(), identification);

                lockFaceService.insertLockFace(lockFace);
            }
        }

    }


    @Override
    public HouseLock selectHouseLockByMac(String mac, String tenantId) {
        return houseLockMapper.selectHouseLockByMac(mac, tenantId);
    }

    @Override
    public HouseLock selectHouseLockByLockName(String lockName, String tenantId) {
        return houseLockMapper.selectHouseLockByLockName(lockName, tenantId);
    }

    @Override
    public List<HouseLock> selectHouseLockByHouseIdAndLockState(String houseId, String lockState) {
        return houseLockMapper.selectHouseLockByHouseIdAndLockState(houseId, lockState);
    }

    @Override
    public int insertLockFace(LockFace lockFace) {
        Long lockId = lockFace.getLockId();
        HouseLock houseLock = houseLockMapper.selectHouseLockByLockId(lockId);
        if (ObjectUtil.isNull(houseLock)) {
            throw new ServiceException("房间锁不存在");
        }
        String format = DateUtil.format(DateUtil.date(), "yyyyMMdd");
        String identification = format + RandomUtil.randomNumbers(8);

        List<Order> orders = orderService.selectEffectiveOrderByHouseId(houseLock.getHouseId());
        // 订单为空，则新增状态
        if (CollectionUtil.isEmpty(orders)) {
            lockDevicesService.createLockFace(lockFace.getImg(), houseLock.getMac(), identification);
            lockFace.setFaceState(LockConstants.FACE_STATE_ENABLED);
        } else {
            // 订单存在
            lockFace.setFaceState(LockConstants.FACE_STATE_DISABLE);
        }


        String houseId = houseLock.getHouseId();
        lockFace.setHouseId(houseId);
        lockFace.setIdentification(identification);
        return lockFaceService.insertLockFace(lockFace);
    }


    @Override
    public int removeLockFace(Long faceId) {
        LockFace lockFace = lockFaceService.selectLockFaceByFaceId(faceId);
        if (ObjectUtil.isNull(lockFace)) {
            throw new ServiceException("人脸不存在");
        }
        Long lockId = lockFace.getLockId();
        HouseLock houseLock = selectHouseLockByLockId(lockId);
        if (ObjectUtil.isNull(houseLock)) {
            throw new ServiceException("锁不存在");
        }
        if (LockConstants.FACE_STATE_ENABLED.equals(lockFace.getFaceState())) {
            lockDevicesService.removeFace(houseLock.getMac(), lockFace.getIdentification());
        }
        // 删除租客人脸则需要更新入住人实名状态 重新授权
        if (lockFace.getUserType().equals(LockConstants.USER_TYPE_TENANT)){
            HouseMember houseMember = houseMemberService.selectHouseMemberByHouseIdAndUserId(lockFace.getHouseId(),lockFace.getUserId());
            if (ObjectUtil.isNotNull(houseMember)){
                houseMember.setAuthState(HouseMemberConstants.AUTH_STATE_NO);
                houseMemberService.updateHouseMember(houseMember);
            }
        }
        return lockFaceService.deleteLockFaceByFaceId(faceId);
    }


    @Override
    public int insertLockPwd(LockPwd lockPwd) {
        Long lockId = lockPwd.getLockId();
        HouseLock houseLock = houseLockMapper.selectHouseLockByLockId(lockId);
        if (ObjectUtil.isNull(houseLock)) {
            throw new ServiceException("房间锁不存在");
        }
        String password = RandomUtil.randomNumbers(6);

        String identification = devicesConfig.getIdentification();
        lockDevicesService.insertLockPwd(lockPwd, houseLock, password, identification);
        lockPwd.setPassword(password);
        lockPwd.setIdentification(identification);
        lockPwd.setHouseId(houseLock.getHouseId());
        lockPwd.setPwdType(LockConstants.PWD_TYPE_TEMPORARY);
        lockPwd.setPwdSource(LockConstants.PWD_SOURCE_ADMIN);
        return lockPwdService.insertLockPwd(lockPwd);
    }


    @Override
    public int removeLockPwd(Long pwdId) {
        LockPwd lockPwd = lockPwdService.selectLockPwdByPwdId(pwdId);
        if (ObjectUtil.isNull(lockPwd)) {
            throw new ServiceException("密码不存在");
        }
        Long lockId = lockPwd.getLockId();
        HouseLock houseLock = selectHouseLockByLockId(lockId);
        if (ObjectUtil.isNull(houseLock)) {
            throw new ServiceException("锁不存在");
        }
        // if (LockConstants.PWD_STATE_EFFECTIVE.equals(lockPwd.getPwdState())) {
        lockDevicesService.removeLockPwd(lockPwd, houseLock);
        // }
        return lockPwdService.deleteLockPwdByPwdId(pwdId);
    }

    @Override
    public TableDataInfo outerOpenDoorRecord(Long lockId, String identification, Date startTime, Date endTime, Integer unlockType, Integer pageNum, Integer pageSize) {
        HouseLock houseLock = selectHouseLockByLockId(lockId);
        if (ObjectUtil.isNull(houseLock)) {
            throw new ServiceException("房间锁不存在");
        }

        StringBuilder params = new StringBuilder();
        params.append("?lockSn=").append(houseLock.getMac());
        if (ObjectUtil.isNotNull(unlockType)) {
            params.append("&unlockType=").append(unlockType);
        }
        if (ObjectUtil.isNotNull(identification)) {
            params.append("&identification=").append(identification);
        }
        if (ObjectUtil.isNotNull(startTime) && ObjectUtil.isNotNull(endTime)) {
            if (DateUtil.compare(startTime, houseLock.getCreateTime()) < 0) {
                throw new ServiceException("开始时间不能早于锁创建时间");
            }


            params.append("&params%5BbeginUnlockTime%5D=").append(DateUtil.format(startTime, "yyyy-MM-dd"));
            params.append("&params%5BendUnlockTime%5D=").append(DateUtil.format(endTime, "yyyy-MM-dd"));
        } else {
            params.append("&params%5BbeginUnlockTime%5D=").append(DateUtil.format(houseLock.getCreateTime(), "yyyy-MM-dd"));
            params.append("&params%5BendUnlockTime%5D=").append(DateUtil.format(DateUtils.getNowDate(), "yyyy-MM-dd"));
        }
        if (ObjectUtil.isNotNull(pageNum) && ObjectUtil.isNotNull(pageSize)) {
            params.append("&pageNum=").append(pageNum);
            params.append("&pageSize=").append(pageSize);
        }
        JSONObject jsonObject = devicesConfig.sendRequest(RequestMethod.GET, null, "/business/unlockLog/list" + params);

        JSONArray jsonArray = jsonObject.getJSONArray("rows");
        List<Map> maps = JSONArray.parseArray(jsonArray.toJSONString(), Map.class);
        if (maps.size() > 0) {
            List<String> identifications = maps.stream().map(x -> x.get("identification").toString()).distinct().collect(Collectors.toList());
            List<LockFace> lockFaces = lockFaceService.selectLockFaceListByIdentifications(identifications);
            Map<String, String> names = lockFaces.stream().collect(Collectors.toMap(LockFace::getIdentification, LockFace::getUserName));
            maps.forEach(x -> {
                String name = names.get(x.get("identification").toString());
                x.put("name", name);
            });
        }

        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(maps);
        rspData.setTotal((Integer) jsonObject.get("total"));
        return rspData;
    }

    @Override
    public int removeLock(Long lockId) {
        HouseLock houseLock = selectHouseLockByLockId(lockId);
        if (ObjectUtil.isNull(houseLock)) {
            throw new ServiceException("房间锁不存在");
        }

        lockDevicesService.removeLock(houseLock);

        // 删除锁信息
        lockFaceService.deleteLockFaceByLockId(lockId);
        lockPwdService.deleteLockPwdByLockId(lockId);
        return houseLockMapper.deleteHouseLockByLockId(lockId);
    }

    @Override
    public List<LockPwd> selectPwdList(HouseLock houseLock) {
        return lockPwdService.selectHousePwdList(houseLock);
    }

    @Override
    @Transactional
    public int insertFlatLockPwd(LockPwd lockPwd) {
        Long lockId = lockPwd.getLockId();
        HouseLock houseLock = houseLockMapper.selectHouseLockByLockId(lockId);
        if (ObjectUtil.isNull(houseLock)) {
            throw new ServiceException("房间锁不存在");
        }
        if (houseLock.getPwdMarginNumber() <= 0) {
            throw new ServiceException("本月暂无临时密码次数");
        }

        String identification = devicesConfig.getIdentification();

        String password = RandomUtil.randomNumbers(6);
        lockDevicesService.insertLockPwd(lockPwd, houseLock, password, identification);

        lockPwd.setPassword(password);
        lockPwd.setIdentification(identification);
        lockPwd.setHouseId(houseLock.getHouseId());
        lockPwd.setPwdType(LockConstants.PWD_TYPE_TEMPORARY);
        lockPwd.setPwdSource(LockConstants.PWD_SOURCE_TENANT);

        int i = lockPwdService.insertLockPwd(lockPwd);

        houseLock.setPwdMarginNumber(houseLock.getPwdMarginNumber() - 1);
        houseLockMapper.updateHouseLock(houseLock);
        return i;
    }

    @Override
    public int updateHouseLockState(String houseId, List<HouseLock> houseLockList) {
        if (CollectionUtil.isNotEmpty(houseLockList)) {
            List<LockFreezeLog> lockFreezeLogList = new ArrayList<>();
            for (HouseLock houseLock : houseLockList) {
                LockFreezeLog lockFreezeLog = new LockFreezeLog();
                lockFreezeLog.setLockId(houseLock.getLockId());
                lockFreezeLog.setCreateBy(houseLock.getUpdateBy());
                lockFreezeLog.setCreateTime(new Date());
                lockFreezeLog.setFreezeType(LockConstants.FREEZE_TYPE_UNFREEZE);
                lockFreezeLog.setOperationType(LockConstants.FREEZE_OPERATE_TYPE_MANUAL);
                lockFreezeLogList.add(lockFreezeLog);
            }
            lockFreezeLogService.batchInsertLockFreezeLog(lockFreezeLogList);
        }
        return houseLockMapper.updateHouseLockState(houseId);
    }

    @Override
    public int disableLockFaceAndFaceState(HouseLock houseLock, LockFace lockFace) {
        lockDevicesService.removeFace(houseLock.getMac(), lockFace.getIdentification());
        lockFace.setFaceState(LockConstants.FACE_STATE_DISABLE);
        return lockFaceService.updateLockFace(lockFace);
    }

    @Override
    public List<HouseLock> selectHouseLockByHouseId(String houseId) {
        return houseLockMapper.selectHouseLockByHouseId(houseId);
    }

    @Override
    public int authorizationLockFace(String mac, LockFace lockFace) {
        lockDevicesService.createLockFace(lockFace.getImg(), mac, lockFace.getIdentification());
        lockFace.setFaceState(LockConstants.FACE_STATE_ENABLED);
        return lockFaceService.updateLockFace(lockFace);
    }

    /**
     * 换房
     *
     * @param houseLock
     * @return
     */
    @Override
    public int changeRoom(HouseLock houseLock) {
        Long lockId = houseLock.getLockId();
        if (ObjectUtil.isNull(lockId) || ObjectUtil.isNull(houseLock.getHouseId())) {
            throw new ServiceException("参数错误");
        }
        HouseLock lock = selectHouseLockByLockId(lockId);
        if (ObjectUtil.isNull(lock)) {
            throw new ServiceException("房间锁不存在");
        }

        if (lock.getHouseId().equals(houseLock.getHouseId())) {
            throw new ServiceException("当前房间和换后房间不能相同");
        }

        removeLock(lockId);

        HouseLock newHouseLock = new HouseLock();
        newHouseLock.setMac(lock.getMac());
        newHouseLock.setBrandId(lock.getBrandId());
        newHouseLock.setBrandName(lock.getBrandName());
        newHouseLock.setModelId(lock.getModelId());
        newHouseLock.setModelName(lock.getModelName());
        newHouseLock.setLockName(lock.getLockName());
        newHouseLock.setHouseId(houseLock.getHouseId());
        newHouseLock.setTenantId(houseLock.getTenantId());
        newHouseLock.setTenantName(houseLock.getTenantName());
        return createHouseLock(newHouseLock);
    }


    /**
     * 变更锁状态
     *
     * @param houseLock
     * @return
     */
    @Override
    public int updateLockStatus(HouseLock houseLock) {
        Long lockId = houseLock.getLockId();
        HouseLock lock = selectHouseLockByLockId(lockId);
        if (ObjectUtil.isNull(lock)) {
            throw new ServiceException("房间锁不存在");
        }

        if (!lock.getLockState().equals(houseLock.getLockState())) {
            // 解冻
            boolean isUnFreeze = houseLock.getLockState().equals(LockConstants.LOCK_STATE_NORMAL);
            List<Order> orders = orderService.selectEffectiveOrderByHouseId(lock.getHouseId());
            if (CollectionUtil.isNotEmpty(orders)) {
                List<LockFace> tenantLockFaces = lockFaceService.selectLockFaceByLockIdAndUserType(lockId, LockConstants.USER_TYPE_TENANT);
                List<LockFace> adminLockFaces = lockFaceService.selectLockFaceByLockIdAndUserType(lockId, LockConstants.USER_TYPE_MANAGER);
                List<LockPwd> lockPwdList = lockPwdService.setLockPwdByLockIdAndPwdState(lockId, LockConstants.PWD_STATE_EFFECTIVE);
                // 锁状态冻结改正常 授权租客人脸 删除管理员人脸 启用临时密码
                if (isUnFreeze) {
                    if (CollectionUtil.isNotEmpty(tenantLockFaces)) {
                        for (LockFace lockFace : tenantLockFaces) {
                            authorizationLockFace(lock.getMac(), lockFace);
                        }
                    }

                    if (CollectionUtil.isNotEmpty(adminLockFaces)) {
                        for (LockFace adminLockFace : adminLockFaces) {
                            if (adminLockFace.getFaceState().equals(LockConstants.FACE_STATE_DISABLE)){
                                continue;
                            }
                            disableLockFaceAndFaceState(lock, adminLockFace);
                        }
                    }


                    if (CollectionUtil.isNotEmpty(lockPwdList)) {
                        for (LockPwd lockPwd : lockPwdList) {
                            lockDevicesService.insertLockPwd(lockPwd, lock, lockPwd.getPassword(), lockPwd.getIdentification());
                        }
                    }


                } else {
                    if (CollectionUtil.isNotEmpty(tenantLockFaces)) {
                        for (LockFace lockFace : tenantLockFaces) {
                            if (lockFace.getFaceState().equals(LockConstants.FACE_STATE_DISABLE)){
                                continue;
                            }
                            disableLockFaceAndFaceState(lock, lockFace);
                        }
                    }

                    if (CollectionUtil.isNotEmpty(adminLockFaces)) {
                        for (LockFace adminLockFace : adminLockFaces) {
                            authorizationLockFace(lock.getMac(), adminLockFace);
                        }
                    }

                    if (CollectionUtil.isNotEmpty(lockPwdList)) {
                        for (LockPwd lockPwd : lockPwdList) {
                            lockDevicesService.removeLockPwd(lockPwd, lock);
                        }
                    }

                }
            }
            LockFreezeLog lockFreezeLog = new LockFreezeLog();
            lockFreezeLog.setLockId(houseLock.getLockId());
            lockFreezeLog.setCreateBy(houseLock.getUpdateBy());
            lockFreezeLog.setFreezeType(isUnFreeze ? LockConstants.FREEZE_TYPE_UNFREEZE : LockConstants.FREEZE_TYPE_FREEZE);
            lockFreezeLog.setOperationType(LockConstants.FREEZE_OPERATE_TYPE_MANUAL);
            lockFreezeLogService.insertLockFreezeLog(lockFreezeLog);
        }

        return updateHouseLock(houseLock);
    }

    @Override
    public void lockAutoFreezeTask() {
        List<HouseLockSetting> houseLockSettings = houseLockSettingService.selectHouseLockSettingByAutoFreezeState(HouseLockSetting.AUTO_FROZEN_STATE_ON);
        if (CollectionUtil.isEmpty(houseLockSettings)) {
            return;
        }
        Map<String, String> autoFrozenMap = houseLockSettings.stream().collect(Collectors.toMap(HouseLockSetting::getTenantId, HouseLockSetting::getAutoFrozenState));
        List<HouseLock> houseLocks = houseLockMapper.selectHouseLockList(new HouseLock());
        for (HouseLock houseLock : houseLocks) {

            if (LockConstants.LOCK_STATE_FREEZE.equals(houseLock.getLockState())) {
                continue;
            }

            String tenantId = houseLock.getTenantId();
            if (autoFrozenMap.containsKey(tenantId)) {
                String autoFrozenState = autoFrozenMap.get(tenantId);
                if (autoFrozenState.equals(HouseLockSetting.AUTO_FROZEN_STATE_ON)) {

                    List<Order> orders = orderService.selectEffectiveOrderByHouseId(houseLock.getHouseId());
                    if (CollectionUtil.isEmpty(orders)) {
                        continue;
                    }
                    List<Order> expiredOrders = orders.stream().filter(x -> DateUtil.compare(x.getCheckOutTime(), new Date()) >= 0).collect(Collectors.toList());
                    if (CollectionUtil.isNotEmpty(expiredOrders)) {
                        houseLock.setLockState(LockConstants.LOCK_STATE_FREEZE);
                        updateLockStatus(houseLock);
                    }
                }
            }
        }


    }

    @Override
    public List<HouseLock> selectHouseLockListAndTenantState(HouseLock houseLock) {
        return houseLockMapper.selectHouseLockListAndTenantState(houseLock);
    }

    @Override
    public int reAuthFace(LockFace lockFace) {
        LockFace lockFace1 = lockFaceService.selectLockFaceByFaceId(lockFace.getFaceId());
        if (ObjectUtil.isNull(lockFace1)) {
            throw new ServiceException("人脸不存在");
        }
        String img = lockFace.getImg();
        if (StrUtil.isEmpty(img)) {
            throw new ServiceException("图片不能为空");
        }

        Long userId = lockFace1.getUserId();
        UserConsumer userConsumer = userConsumerService.selectUserConsumerByUserId(userId);
        if (ObjectUtil.isNull(userConsumer)) {
            throw new ServiceException("租客不存在");
        }

        AjaxResult ajaxResult = aliAuthService.faceAuth(userConsumer.getUserName(), userConsumer.getCardNumber(), img);
        if (!ajaxResult.get("code").equals(200)) {
            log.error("人脸信息认证失败，原因：{}", ajaxResult.get("msg"));
            throw new ServiceException("人脸信息认证失败");
        }

        lockFace1.setImg(img);
        lockFace1.setUpdateBy(lockFace.getUpdateBy());
        HouseLock houseLock = selectHouseLockByLockId(lockFace1.getLockId());
        if (ObjectUtil.isNull(houseLock)) {
            throw new ServiceException("房间锁不存在");
        }

        // 启用状态重新授权人脸
        if (lockFace1.getFaceState().equals(LockConstants.FACE_STATE_ENABLED)) {
            lockDevicesService.removeFace(houseLock.getMac(), lockFace1.getIdentification());
            authorizationLockFace(houseLock.getMac(), lockFace1);
        }

        return lockFaceService.updateLockFace(lockFace1);
    }

    /**
     * 变更房管员
     *
     * @param houseId
     * @param houseManagerId
     */
    @Override
    @Transactional
    public void updateHouseManager(String houseId, Long houseManagerId) {
        List<HouseLock> houseLocks = selectHouseLockByHouseId(houseId);
        if (CollectionUtil.isEmpty(houseLocks)) {
            return;
        }
        House house = houseService.selectHouseByHouseId(houseId);
        BizUserBusiness bizUserBusiness = bizUserBusinessService.selectBizUserBusinessByUserId(house.getHouseManagerId(), house.getTenantId());
        BizUserBusiness newHouseManager = bizUserBusinessService.selectBizUserBusinessByUserId(houseManagerId, house.getTenantId());

        for (HouseLock houseLock : houseLocks) {
            String identification = devicesConfig.getIdentification();
            LockFace lockFace = new LockFace();
            LockFace face = lockFaceService.selectFaceByLockIdAndUserIdAndUserType(houseLock.getLockId(), bizUserBusiness.getUserId(), LockConstants.USER_TYPE_MANAGER);
            if (ObjectUtil.isNotNull(face)) {

                lockFace.setUserType(LockConstants.USER_TYPE_MANAGER);
                lockFace.setLockId(houseLock.getLockId());
                lockFace.setImg(newHouseManager.getFaceImage());
                lockFace.setIdentification(identification);
                lockFace.setUserId(newHouseManager.getUserId());
                lockFace.setUserName(newHouseManager.getUserName());

                // 非冻结状态下 直接删除管理员人脸
                if (houseLock.getLockState().equals(LockConstants.LOCK_STATE_NORMAL)) {
                    lockFace.setFaceState(LockConstants.FACE_STATE_DISABLE);
                } else {
                    lockFace.setFaceState(LockConstants.FACE_STATE_ENABLED);
                    lockDevicesService.removeFace(houseLock.getMac(), face.getIdentification());
                    lockDevicesService.createLockFace(lockFace.getImg(), houseLock.getMac(), lockFace.getIdentification());
                }

                lockFaceService.deleteLockFaceByFaceId(face.getFaceId());
                lockFaceService.insertLockFace(lockFace);
            }
        }
    }

    @Override
    public void workOrderAuthPwd(WorkOrderPwdRecord workOrderPwdRecord) {
        String houseId = workOrderPwdRecord.getHouseId();
        List<HouseLock> houseLocks = selectHouseLockByHouseId(houseId);
        if (CollectionUtil.isEmpty(houseLocks)) {
            throw new ServiceException("房间锁不存在");
        }

        String password = RandomUtil.randomNumbers(6);
        String identification = devicesConfig.getIdentification();
        for (HouseLock houseLock : houseLocks) {
            LockPwd lockPwd = new LockPwd();
            lockPwd.setOrderId(workOrderPwdRecord.getWorkOrderId());

            lockPwd.setAuthStartTime(workOrderPwdRecord.getPwdStartTime());
            lockPwd.setAuthEndTime(workOrderPwdRecord.getPwdEndTime());
            lockPwd.setCreateBy(workOrderPwdRecord.getReqUserName());
            lockPwd.setTenantId(workOrderPwdRecord.getTenantId());

            lockDevicesService.insertLockPwd(lockPwd, houseLock, password, identification);
            lockPwd.setPassword(password);
            lockPwd.setIdentification(identification);
            lockPwd.setHouseId(houseLock.getHouseId());
            lockPwd.setPwdType(LockConstants.PWD_TYPE_TEMPORARY);
            lockPwd.setPwdSource(LockConstants.PWD_SOURCE_ADMIN);
            lockPwdService.insertLockPwd(lockPwd);

        }

        Date pwdStartTime = workOrderPwdRecord.getPwdStartTime();
        Date pwdEndTime = workOrderPwdRecord.getPwdEndTime();
        String pwdValidity = DateUtil.format(pwdStartTime, "yyyy-MM-dd HH:mm") +"~" + DateUtil.format(pwdEndTime, "HH:mm");

        boolean smsWithData = smsUtils.sendTemplateSmsWithData(workOrderPwdRecord.getReqPhone(), smsConfig.getWorkOrderPwdApplyConsentCode(), new String[]{
                workOrderPwdRecord.getPremisesAddress(),"看房",password,pwdValidity});
        if (!smsWithData) {
           throw new ServiceException("短信发送失败");
        }
    }

    @Override
    public void removeLockPwdAndLockFace(String houseId, String userType) {
        List<LockPwd> lockPwdList = lockPwdService.selectLockPwdListAndHouseId(houseId);
        if (CollectionUtil.isNotEmpty(lockPwdList)) {
            for (LockPwd lockPwd : lockPwdList) {
                removeLockPwd(lockPwd.getPwdId());
            }
        }


        List<LockFace> lockFaceList = lockFaceService.selectLockFaceListAndHouseIdAndUserType(houseId, userType);
        if (CollectionUtil.isNotEmpty(lockFaceList)) {
            for (LockFace lockFace : lockFaceList) {
                removeLockFace(lockFace.getFaceId());
            }
        }
    }

    @Override
    public void removeLockPwdAndLockFace(String orderId) {
        lockFaceService.deleteLockFaceByOrderId(orderId);
        lockPwdService.deleteLockPwdByOrderId(orderId);
    }
}

